package algorithms.question.class09;

import common.util.MyUtil;

/**
 * 定义何为step sum？
 * 比如680，680 + 68 + 6 = 754，680的step sum叫754
 * 给定一个正数num，判断它是不是某个数的step sum
 *
 * @author guichang
 * @date 2021/8/6
 */

@SuppressWarnings("all")
public class Code5_某个数的StepSum {

    public static void main(String[] args) {
        MyUtil.print(stepSum(680));
        MyUtil.print(stepSumFor(754));
    }

    /**
     * 如果x是某个数y的步骤和，那么y必定小于x，使用二分即可
     */
    public static int stepSumFor(int x) {
        if (x <= 0) {
            return -1;
        }
        int l = 1;
        int r = x;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            int stepSum = stepSum(mid);
            if (stepSum == x) {
                return mid;
            }
            if (stepSum < x) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 计算某个数的步骤和
     */
    private static int stepSum(int y) {
        int sum = y;
        while (y > 0) {
            y = y / 10;
            sum += y;
        }
        return sum;
    }

}